package com.platform.mapper;
import com.alibaba.fastjson.JSONObject;
import com.platform.dao.ApiUserMapper;
import com.platform.dao.UserHotelMapper;
import com.platform.dao.UserInviteesMapper;
import com.platform.entity.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.ZXingUtil;
import com.platform.utils.DateUtil;
import com.platform.util.result.ResponseCode;
import com.platform.util.result.ResponseUtil;
import com.platform.utils.sqlUtils.SqlParameter;
import com.platform.util.wechat.WechatUtil;
import com.platform.utils.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @version: V1.0
 * @author:weigangchen
 * @className: WeChatServiceImpl
 * @packageName: com.select.school.service.wxApplet.impl
 * @description:
 * @data: 2020-8-13
 **/

@Service
public class WeChatServiceImpl extends ApiBaseAction implements WeChatService {

    @Autowired
    private ApiUserMapper userMapper;

    @Autowired
    protected HttpServletRequest request;
    @Resource
    private UserInviteesMapper userInviteesMapper;

    @Resource
    private UserHotelMapper userHotelMapper;

    @Override
    public String decrypt(WeChatDecryptParamDTO param) {
        try {

            String encryptedData = param.getEncryptedData();
            String iv = param.getIv();
            //解析加密数据
           String result = WechatUtil.decryptPhoneNumber(param.getSessionKey(),encryptedData, iv);
            logger.info(result);
            JSONObject resJson = JSONObject.parseObject(result);
            String openid = param.getOpenid();
            String phoneNumber = resJson.getString("phoneNumber");
            //更新用户手机号
            int res = userMapper.updatePhoneNum(SqlParameter.getParameter()
                    .addUpdate("openid", openid)
                    .addUpdate("phoneNumber", phoneNumber).getMap());
            if (res > 0) {
                return ResponseUtil.setResult(ResponseCode.SUCCESS, result);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.setResult(ResponseCode.ERROR);
        }
        return ResponseUtil.setResult(ResponseCode.SUCCESS);

    }

    @Override
    public String getQRcode(String openid,String  goodId) {
        //根据openid查询当前用户id
        UserVo user = userMapper.detail(openid);
         if (user == null) {
            ResponseUtil.setResult(ResponseCode.ACCOUNT_NOT);
        }
        String userId = user.getUserId().toString();
        String picName = "QRcode-" + userId + goodId + ".jpg";//图片名称
        String imagePath = ResourceUtil.getConfigByName("qrcode.imgpath") + picName;//服务器存放图片地址
        String content = "https://www.desmart.com.cn/qcs/mini/index.html?uid=" + userId + "&" + "gid=" + goodId;

        String path = "E:\\apache-tomcat-desmartNew\\webapps\\qcs\\image\\" + picName;
       // String path = "E:\\text" + picName;
        try {
            boolean result = ZXingUtil.createQrCode(new FileOutputStream(new File(path)), content, 900, "JPEG");
            //  boolean result = QRcodeUtil.createQRCode(7, strURL, "png", imagePath);
            if (result) {

                userMapper.updateByOpenId(SqlParameter.getParameter()
                        .addUpdate("qrcodeUrl", imagePath)
                        .addUpdate("weixinOpenid", openid).getMap());
                String imageUrl = "https://www.desmart.com.cn/qcs/image/"+picName;
                return ResponseUtil.setResult(ResponseCode.SUCCESS, imageUrl);

            } else {
                return ResponseUtil.setResult(ResponseCode.ERROR);
            }
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public String createInvite(InviteParamVo param) {
        try {
            //是否自己扫自己的码
            if(param.getUserId()== param.getParentId()){
                return ResponseUtil.setResult(ResponseCode.INVITE_BIND_RELATION_SAME);
            }
            //查询数据库是否有该条数据
            Map<String,Object> map = new HashMap<>();
            map.put("userId",param.getUserId());
            map.put("parentId",param.getParentId());
            List<UserInvitees> userInviteesList=userInviteesMapper.queryList(map);
            if (userInviteesList.size()>0){
                return ResponseUtil.setResult(ResponseCode.INVITE_BIND_RELATION_EXISTS);
            }
            UserVo userVo = userMapper.queryObject(param.getParentId());

            if (userVo == null) {
                return ResponseUtil.setResult(ResponseCode.ERROR);
            }

                UserInvitees invitees = new UserInvitees();
                invitees.setUserId(param.getUserId());
                invitees.setParentId(param.getParentId());
                invitees.setGoodId(param.getGoodId());
                invitees.setCreateTime(DateUtil.getToDay("yyyy-MM-dd HH:mm:ss"));
                int res = userInviteesMapper.insertInvitees(invitees);
                if (res < 0) {
                    return ResponseUtil.setResult(ResponseCode.ERROR);
                }


        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.setResult(ResponseCode.ERROR);
        }
        return ResponseUtil.setResult(ResponseCode.SUCCESS);
    }

    @Override
    public String saveHotel(HotelVo hotelVo) {
        try {
            UserVo userVo = userMapper.queryObject(hotelVo.getId());
            if (userVo == null){
                ResponseUtil.setResult(ResponseCode.ERROR);
            }
            UserHotelEntity userHotelEntity = new UserHotelEntity();
            userHotelEntity.setUserId(hotelVo.getUserId());
            userHotelEntity.setHotelId(hotelVo.getHotelId());
           int res =  userHotelMapper.insertHotel(userHotelEntity);
           if (res<0){
               return ResponseUtil.setResult(ResponseCode.ERROR);
           }


        }catch (Exception e){
            e.printStackTrace();
            return ResponseUtil.setResult(ResponseCode.ERROR);
        }

        return  ResponseUtil.setResult(ResponseCode.SUCCESS);

    }
}